package mytest;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import net.sourceforge.opencamera.R;

import java.util.List;

public class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.PhotoViewHolder> {

    private Context context;
    private List<String> photoPaths; // 假设照片路径是存储为 String 的 URL 或本地路径
    private OnItemClickListener onItemClickListener;

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.onItemClickListener = listener;
    }

    // 构造函数，传入上下文和图片路径列表
    public PhotoAdapter(Context context, List<String> photoPaths) {
        this.context = context;
        this.photoPaths = photoPaths;
    }

    @NonNull
    @Override
    public PhotoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 使用布局填充器加载每个列表项的布局
        View view = LayoutInflater.from(context).inflate(R.layout.item_photo, parent, false);
        return new PhotoViewHolder(view, onItemClickListener);
    }

    @Override
    public void onBindViewHolder(@NonNull PhotoViewHolder holder, int position) {
        // 获取当前位置的照片路径
        String photoPath = photoPaths.get(position);

        // 使用 Glide 或其他图片加载库加载图片到 ImageView 中
        Glide.with(context)
                .load(photoPath)
                .into(holder.photoImageView);
    }

    @Override
    public int getItemCount() {
        return photoPaths.size(); // 列表中照片的数量
    }

    // ViewHolder 类，持有每个列表项中的视图
    public static class PhotoViewHolder extends RecyclerView.ViewHolder {
        public ImageView photoImageView;

        public PhotoViewHolder(@NonNull View itemView, final OnItemClickListener listener) {
            super(itemView);
            photoImageView = itemView.findViewById(R.id.imageView_photo);

            // 设置点击事件监听器
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        int position = getAdapterPosition();
                        if (position != RecyclerView.NO_POSITION) {
                            listener.onItemClick(position);
                        }
                    }
                }
            });
        }
    }
}